/**
 * 游戏主入口文件
 * 负责初始化和启动整个游戏系统
 */

import GameManager from './game-manager.js';
import { DebugUtils } from './utils.js';

/**
 * 游戏应用类
 */
class GameApp {
    constructor() {
        this.gameManager = null;
        this.isInitialized = false;
        this.loadingElement = null;
        this.errorElement = null;
    }

    /**
     * 初始化游戏应用
     */
    async init() {
        try {
            this.showLoading('正在初始化游戏...');
            
            // 检查浏览器兼容性
            this.checkBrowserCompatibility();
            
            // 创建游戏管理器
            this.gameManager = new GameManager();
            
            // 初始化游戏管理器
            await this.gameManager.init();
            
            this.hideLoading();
            this.isInitialized = true;
            
            DebugUtils.log('游戏应用初始化完成');
            
            // 启动游戏
            this.start();
            
        } catch (error) {
            this.hideLoading();
            this.showError('游戏初始化失败', error);
            DebugUtils.error('游戏应用初始化失败', error);
        }
    }

    /**
     * 启动游戏
     */
    start() {
        if (!this.isInitialized || !this.gameManager) {
            throw new Error('游戏尚未初始化');
        }
        
        this.gameManager.start();
        DebugUtils.log('游戏已启动');
    }

    /**
     * 停止游戏
     */
    stop() {
        if (this.gameManager) {
            this.gameManager.stop();
            DebugUtils.log('游戏已停止');
        }
    }

    /**
     * 重启游戏
     */
    async restart() {
        this.stop();
        await this.init();
    }

    /**
     * 检查浏览器兼容性
     */
    checkBrowserCompatibility() {
        const features = {
            canvas: !!document.createElement('canvas').getContext,
            localStorage: !!window.localStorage,
            requestAnimationFrame: !!window.requestAnimationFrame,
            es6: () => {
                try {
                    new Function('class Test {}');
                    return true;
                } catch (e) {
                    return false;
                }
            }
        };

        const missingFeatures = [];
        
        Object.entries(features).forEach(([feature, supported]) => {
            const isSupported = typeof supported === 'function' ? supported() : supported;
            if (!isSupported) {
                missingFeatures.push(feature);
            }
        });

        if (missingFeatures.length > 0) {
            throw new Error(`浏览器不支持以下功能: ${missingFeatures.join(', ')}`);
        }

        DebugUtils.log('浏览器兼容性检查通过');
    }

    /**
     * 显示加载界面
     * @param {string} message 
     */
    showLoading(message = '正在加载...') {
        this.hideError();
        
        if (!this.loadingElement) {
            this.loadingElement = document.createElement('div');
            this.loadingElement.id = 'game-loading';
            this.loadingElement.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.8);
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                z-index: 10000;
                color: white;
                font-family: Arial, sans-serif;
            `;
            
            this.loadingElement.innerHTML = `
                <div class="loading-spinner" style="
                    width: 50px;
                    height: 50px;
                    border: 3px solid #333;
                    border-top: 3px solid #4a90e2;
                    border-radius: 50%;
                    animation: spin 1s linear infinite;
                    margin-bottom: 20px;
                "></div>
                <div class="loading-text" style="font-size: 18px;">${message}</div>
            `;
            
            // 添加旋转动画
            if (!document.getElementById('loading-animation')) {
                const style = document.createElement('style');
                style.id = 'loading-animation';
                style.textContent = `
                    @keyframes spin {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                `;
                document.head.appendChild(style);
            }
            
            document.body.appendChild(this.loadingElement);
        } else {
            this.loadingElement.style.display = 'flex';
            const textElement = this.loadingElement.querySelector('.loading-text');
            if (textElement) {
                textElement.textContent = message;
            }
        }
    }

    /**
     * 隐藏加载界面
     */
    hideLoading() {
        if (this.loadingElement) {
            this.loadingElement.style.display = 'none';
        }
    }

    /**
     * 显示错误信息
     * @param {string} message 
     * @param {Error} error 
     */
    showError(message, error = null) {
        this.hideLoading();
        
        if (!this.errorElement) {
            this.errorElement = document.createElement('div');
            this.errorElement.id = 'game-error';
            this.errorElement.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.9);
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                z-index: 10001;
                color: white;
                font-family: Arial, sans-serif;
                text-align: center;
                padding: 20px;
                box-sizing: border-box;
            `;
            
            document.body.appendChild(this.errorElement);
        }
        
        const errorDetails = error ? error.message : '未知错误';
        
        this.errorElement.innerHTML = `
            <div style="
                max-width: 600px;
                background: rgba(255, 0, 0, 0.1);
                border: 2px solid #ff4757;
                border-radius: 10px;
                padding: 30px;
            ">
                <h2 style="color: #ff4757; margin-bottom: 20px;">游戏错误</h2>
                <p style="font-size: 18px; margin-bottom: 15px;">${message}</p>
                <p style="font-size: 14px; color: #ccc; margin-bottom: 20px;">${errorDetails}</p>
                <button id="retry-button" style="
                    background: #4a90e2;
                    color: white;
                    border: none;
                    padding: 12px 24px;
                    border-radius: 5px;
                    font-size: 16px;
                    cursor: pointer;
                    margin-right: 10px;
                ">重试</button>
                <button id="reload-button" style="
                    background: #666;
                    color: white;
                    border: none;
                    padding: 12px 24px;
                    border-radius: 5px;
                    font-size: 16px;
                    cursor: pointer;
                ">刷新页面</button>
            </div>
        `;
        
        this.errorElement.style.display = 'flex';
        
        // 添加按钮事件
        const retryButton = this.errorElement.querySelector('#retry-button');
        const reloadButton = this.errorElement.querySelector('#reload-button');
        
        if (retryButton) {
            retryButton.addEventListener('click', () => {
                this.hideError();
                this.restart();
            });
        }
        
        if (reloadButton) {
            reloadButton.addEventListener('click', () => {
                window.location.reload();
            });
        }
    }

    /**
     * 隐藏错误信息
     */
    hideError() {
        if (this.errorElement) {
            this.errorElement.style.display = 'none';
        }
    }

    /**
     * 监听页面卸载事件
     */
    setupUnloadHandlers() {
        window.addEventListener('beforeunload', (e) => {
            if (this.gameManager && this.isInitialized) {
                // 尝试保存游戏
                try {
                    this.gameManager.saveGame();
                } catch (error) {
                    DebugUtils.error('自动保存失败', error);
                }
            }
        });
        
        // 页面隐藏时暂停游戏
        document.addEventListener('visibilitychange', () => {
            if (this.gameManager) {
                if (document.hidden) {
                    this.gameManager.stop();
                } else {
                    this.gameManager.start();
                }
            }
        });
    }

    /**
     * 设置全局错误处理
     */
    setupGlobalErrorHandling() {
        window.addEventListener('error', (e) => {
            DebugUtils.error('全局错误', e.error);
            this.showError('游戏运行时出现错误', e.error);
        });
        
        window.addEventListener('unhandledrejection', (e) => {
            DebugUtils.error('未处理的Promise拒绝', e.reason);
            this.showError('游戏运行时出现异步错误', e.reason);
        });
    }
}

/**
 * 游戏入口点
 */
async function main() {
    // 等待DOM加载完成
    if (document.readyState === 'loading') {
        await new Promise(resolve => {
            document.addEventListener('DOMContentLoaded', resolve);
        });
    }
    
    // 创建游戏应用实例
    const gameApp = new GameApp();
    
    // 设置错误处理
    gameApp.setupGlobalErrorHandling();
    
    // 设置页面卸载处理
    gameApp.setupUnloadHandlers();
    
    // 初始化并启动游戏
    await gameApp.init();
    
    // 将游戏应用实例挂载到全局，便于调试
    if (window.GAME_CONFIG?.GAME?.DEBUG_MODE) {
        window.gameApp = gameApp;
        DebugUtils.log('游戏应用实例已挂载到 window.gameApp');
    }
}

// 启动游戏
main().catch(error => {
    console.error('游戏启动失败:', error);
    
    // 显示启动失败的错误信息
    const errorDiv = document.createElement('div');
    errorDiv.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(255, 0, 0, 0.9);
        color: white;
        padding: 20px;
        border-radius: 10px;
        text-align: center;
        z-index: 10002;
        font-family: Arial, sans-serif;
    `;
    errorDiv.innerHTML = `
        <h3>游戏启动失败</h3>
        <p>${error.message}</p>
        <button onclick="window.location.reload()" style="
            background: white;
            color: #333;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
        ">刷新页面</button>
    `;
    document.body.appendChild(errorDiv);
});

// 导出主函数以便测试
export { main, GameApp };

